package com.umeox.watch.moto.dataservice.mqtt.rpc;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.umeox.moto.common.log.Logger;
import com.umeox.watch.moto.dataservice.DataProvider;
import com.umeox.watch.moto.dataservice.base.BaseApp;
import com.umeox.watch.moto.dataservice.constants.Constants;
import com.umeox.watch.moto.dataservice.constants.MqttConstants;
import com.umeox.watch.moto.dataservice.mqtt.Topic;
import com.umeox.watch.moto.dataservice.mqtt.bean.MakeFriendDTO;
import com.umeox.watch.moto.dataservice.mqtt.debug.DebugUtils;
import com.umeox.watch.moto.dataservice.mqtt.impl.MqttServiceDelegate;
import com.umeox.watch.moto.dataservice.services.HeartRateMeasureService;
import com.umeox.watch.moto.dataservice.services.LocationService;
import com.umeox.watch.moto.dataservice.utils.LogUtils;

import java.util.List;


/**
 * Created by Rambo 2020/5/7
 * Describe:
 */
public class ResponseRpc extends BaseRpc {

    private static final int STATUS_CALLING = 1;
    private static final int STATUS_CANCEL_CALLING = 2;
    private static final int TYPE_VIDEO_CALL = 1;
    private static final int TYPE_VOICE_CALL = 2;
    private static final int TYPE_PTT_CALL = 3;

    private static final int REMOTE_POWER_OFF = 1;
    private static final int REMOTE_REBOOT = 2;
    private static final int REMOTE_HEART_MEASURE = 3;
    private static final int REMOTE_THUMBS_UP = 6;


    private ResponseRpc(Builder builder) {
        this.responseTopic = Topic.CLOUD_RPC_REPLY_TOPIC_PREFIX + getResponseCode(builder.topic);
        this.params = builder.params;
        this.method = builder.method;
    }

    private String getResponseCode(String topic) {
        int index = topic.lastIndexOf("/");
        return topic.substring(index + 1);
    }

    @SuppressLint("WrongConstant")
    @Override
    public void handleOrResponse() {
        JSONObject temp = new JSONObject();
        if (isResponseDeviceStatus()) {
            temp.put("isOnline", true);
            temp.put("battery", BaseApp.getInstance().getBatteryLevel());
            temp.put("stepValue", DataProvider.getStepsToday());
            temp.put("firmwareVersion", Build.DISPLAY);
            MqttServiceDelegate.rpcResponse(responseTopic, method, temp, null);
        } else if (isRequestLocation()) {
            MqttServiceDelegate.rpcResponse(responseTopic, method, temp, null);
            if (params != null) {
                String cmdId = params.getString("reqId");
                int locPriority = params.getIntValue("locPriority");
                Logger.d("远程定位请求>>>reqId:" + cmdId + ",locPriority=" + locPriority);
                LocationService.cmdReqLocation(BaseApp.getInstance(), cmdId, locPriority);
            }
        } else if (isRequestVoipCall()) {
            LogUtils.saveMqttLog("收到音视频来电");
            MqttServiceDelegate.rpcResponse(responseTopic, method, temp, null);
            LogUtils.saveMqttLog("回复服务端的音视频来电RPC请求：responseTopic=" + responseTopic + ",method=" + method);
            //服务器请求视频通话
            String channel = params.getString("channel");
            String fuid = params.getString("fromMemberId");
            int status = params.getIntValue("status");
            int type = params.getIntValue("type");
            if (status == STATUS_CALLING) {
                if (type == TYPE_VIDEO_CALL) {//请求视频呼叫
                    Logger.d("收到视频通话指令");
                    //声网视频电话呼叫
                    Logger.i("Send Broadcast[" + Constants.ACTION_INCOMING_VIDEO_CALL + "]");
                    Intent intent = new Intent(Constants.ACTION_INCOMING_VIDEO_CALL);
                    intent.putExtra("channel", channel);
                    intent.putExtra("fuid", fuid);
                    intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES | Intent.FLAG_RECEIVER_FOREGROUND | Constants.FLAG_RECEIVER_INCLUDE_BACKGROUND);
                    BaseApp.getInstance().sendBroadcast(intent);
                } else if (type == TYPE_VOICE_CALL) {//请求语音呼叫
                    Logger.d("收到语音通话指令");
                    //声网视频电话呼叫
                    Logger.i("Send Broadcast[" + Constants.ACTION_INCOMING_VOIP_CALL + "]");
                    Intent intent = new Intent(Constants.ACTION_INCOMING_VOIP_CALL);
                    intent.putExtra("channel", channel);
                    intent.putExtra("fuid", fuid);
                    intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES | Intent.FLAG_RECEIVER_FOREGROUND | Constants.FLAG_RECEIVER_INCLUDE_BACKGROUND);
                    BaseApp.getInstance().sendBroadcast(intent);
                } else if (type == TYPE_PTT_CALL) { //PTT
                    Logger.d("收到PTT通话指令");
                    //声网视频电话呼叫
                    Logger.i("Send Broadcast[" + Constants.ACTION_INCOMING_PTT_CALL + "]");
                    Intent intent = new Intent(Constants.ACTION_INCOMING_PTT_CALL);
                    intent.putExtra("channel", channel);
                    intent.putExtra("fuid", fuid);
                    intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES | Intent.FLAG_RECEIVER_FOREGROUND | Constants.FLAG_RECEIVER_INCLUDE_BACKGROUND);
                    BaseApp.getInstance().sendBroadcast(intent);
                }
            } else if (status == STATUS_CANCEL_CALLING) {
                Logger.d("收到对方已挂断指令");
                //声网视频电话呼叫
                Logger.i("Send Broadcast[" + Constants.ACTION_CANCEL_AGORA_CALL + "]");
                Intent intent = new Intent(Constants.ACTION_CANCEL_AGORA_CALL);
                intent.putExtra("channel", channel);
                intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES | Intent.FLAG_RECEIVER_FOREGROUND | Constants.FLAG_RECEIVER_INCLUDE_BACKGROUND);
                BaseApp.getInstance().sendBroadcast(intent);
            }
        } else if (isRequestOperateDevice()) {
            MqttServiceDelegate.rpcResponse(responseTopic, method, temp, null);
            int type = params.getIntValue("type"); //1 关机 2：重启
            switch (type) {
                case REMOTE_POWER_OFF:
                    Logger.d("收到远程关机指令");
                    Logger.i("Send Broadcast[" + Constants.ACTION_REMOTE_POWEROFF + "]");
                    Intent powerOffIntent = new Intent(Constants.ACTION_REMOTE_POWEROFF);
                    powerOffIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES | Intent.FLAG_RECEIVER_FOREGROUND | Constants.FLAG_RECEIVER_INCLUDE_BACKGROUND);
                    BaseApp.getInstance().sendBroadcast(powerOffIntent);
                    break;
                case REMOTE_REBOOT:
                    Logger.d("收到远程重启指令");
                    Logger.i("Send Broadcast[" + Constants.ACTION_REMOTE_REBOOT + "]");
                    Intent rebootIntent = new Intent(Constants.ACTION_REMOTE_REBOOT);
                    rebootIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES | Intent.FLAG_RECEIVER_FOREGROUND | Constants.FLAG_RECEIVER_INCLUDE_BACKGROUND);
                    BaseApp.getInstance().sendBroadcast(rebootIntent);
                    break;
                case REMOTE_HEART_MEASURE: {
                    JSONObject dataJson = params.getJSONObject("data");
                    String code = "3#" + dataJson.getString("code");
                    Logger.d("收到远程心率测量指令,测量指令code=" + code);
                    HeartRateMeasureService.cmdHeartRateDetection(BaseApp.getInstance(), code);
                }
                break;
                case REMOTE_THUMBS_UP: {
                    JSONObject dataJson = params.getJSONObject("data");
                    int source = dataJson.getIntValue("source");
                    Logger.d("收到点赞指令,source=" + source);
                    Intent thumbsUpIntent = new Intent(Constants.ACTION_THUMBS_UP);
                    thumbsUpIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES | Intent.FLAG_RECEIVER_FOREGROUND | Constants.FLAG_RECEIVER_INCLUDE_BACKGROUND);
                    BaseApp.getInstance().sendBroadcast(thumbsUpIntent);
                }
                break;
            }
        } else if (isRequestDeviceFriend()) {
            MqttServiceDelegate.rpcResponse(responseTopic, method, temp, null);
            if (!params.isEmpty()) {
                //解析数据得到交友结果并通知交友应用交友是否成功
                JSONArray friendsJSONArray = params.getJSONArray("friends");
                if (!friendsJSONArray.isEmpty()) {
                    List<MakeFriendDTO> list = JSONObject.parseArray(friendsJSONArray.toJSONString(), MakeFriendDTO.class);
                    int makeFriendResult = 0;
                    for (MakeFriendDTO makeFriendDTO : list) {
                        makeFriendResult |= makeFriendDTO.status;
                    }
                    Logger.i("Send Broadcast[" + Constants.ACTION_MAKE_FRIEND + "]");
                    Intent intent = new Intent(Constants.ACTION_MAKE_FRIEND);
                    intent.putExtra(Constants.EXTRA_MAKE_FRIEND_STATUS, makeFriendResult);
                    intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES | Intent.FLAG_RECEIVER_FOREGROUND | Constants.FLAG_RECEIVER_INCLUDE_BACKGROUND);
                    BaseApp.getInstance().sendBroadcast(intent);
                }
            }
        } else if (isRequestDeviceDebugData()) {

            int type = params.getIntValue("type");
            if (type == 1) { //获取设备信息
                JSONObject dataJson = params.getJSONObject("data");
                String keys = dataJson.getString("keys");
                if (keys.contains("ALL")) {
                    temp.put(MqttConstants.Attributes.HOT_VER, DebugUtils.buildHotVer());
                    temp.put(MqttConstants.Attributes.DEVICE_CONFIG, DebugUtils.buildDeviceConfig());
                    temp.put(MqttConstants.Attributes.HOLDER_INFO, DebugUtils.buildHolderInfo());
                    temp.put(MqttConstants.Attributes.CONTACTS, DebugUtils.buildContactsList());
                    temp.put(MqttConstants.Attributes.FRIENDS, DebugUtils.buildFriendsList());
                    temp.put(MqttConstants.Attributes.LOCATION_FREQ, DebugUtils.buildLocationFreqList());
                    temp.put(MqttConstants.Attributes.ALARM, DebugUtils.buildAlarmList());
                    temp.put(MqttConstants.Attributes.CLASS_MODE, DebugUtils.buildClassModeList());
                    temp.put(MqttConstants.Attributes.SPORT_CHALLENGE, DebugUtils.buildSportChallengeList());
                    temp.put(MqttConstants.Attributes.QURAN_LEARN, DebugUtils.buildQuranLearnList());
                    temp.put(MqttConstants.Attributes.PRAYER_SETTING, DebugUtils.buildPrayerSettings());
                    temp.put("prayerParam", DebugUtils.buildPrayerParam());
                    temp.put("networkInfo", DebugUtils.buildNetworkInfo());
                    temp.put("deviceInfo", DebugUtils.buildDeviceInfo());
                }

                if (keys.contains(MqttConstants.Attributes.HOT_VER)) {
                    temp.put(MqttConstants.Attributes.HOT_VER, DebugUtils.buildHotVer());
                }
                if (keys.contains(MqttConstants.Attributes.DEVICE_CONFIG)) {
                    temp.put(MqttConstants.Attributes.DEVICE_CONFIG, DebugUtils.buildDeviceConfig());
                }
                if (keys.contains(MqttConstants.Attributes.HOLDER_INFO)) {
                    temp.put(MqttConstants.Attributes.HOLDER_INFO, DebugUtils.buildHolderInfo());
                }
                if (keys.contains(MqttConstants.Attributes.CONTACTS)) {
                    temp.put(MqttConstants.Attributes.CONTACTS, DebugUtils.buildContactsList());
                }
                if (keys.contains(MqttConstants.Attributes.FRIENDS)) {
                    temp.put(MqttConstants.Attributes.FRIENDS, DebugUtils.buildFriendsList());
                }
                if (keys.contains(MqttConstants.Attributes.LOCATION_FREQ)) {
                    temp.put(MqttConstants.Attributes.LOCATION_FREQ, DebugUtils.buildLocationFreqList());
                }
                if (keys.contains(MqttConstants.Attributes.ALARM)) {
                    temp.put(MqttConstants.Attributes.ALARM, DebugUtils.buildAlarmList());
                }
                if (keys.contains(MqttConstants.Attributes.CLASS_MODE)) {
                    temp.put(MqttConstants.Attributes.CLASS_MODE, DebugUtils.buildClassModeList());
                }
                if (keys.contains(MqttConstants.Attributes.SPORT_CHALLENGE)) {
                    temp.put(MqttConstants.Attributes.SPORT_CHALLENGE, DebugUtils.buildSportChallengeList());
                }
                if (keys.contains(MqttConstants.Attributes.QURAN_LEARN)) {
                    temp.put(MqttConstants.Attributes.QURAN_LEARN, DebugUtils.buildQuranLearnList());
                }
                if (keys.contains(MqttConstants.Attributes.PRAYER_SETTING)) {
                    temp.put(MqttConstants.Attributes.PRAYER_SETTING, DebugUtils.buildPrayerSettings());
                }
                if (keys.contains("prayerParam")) {
                    temp.put("prayerParam", DebugUtils.buildPrayerParam());
                }
                if (keys.contains("networkInfo")) {
                    temp.put("networkInfo", DebugUtils.buildNetworkInfo());
                }
                if (keys.contains("deviceInfo")) {
                    temp.put("deviceInfo", DebugUtils.buildDeviceInfo());
                }

                MqttServiceDelegate.rpcResponse(responseTopic, method, temp, null);
            }
        }
    }


    public static class Builder {
        private String topic;
        private JSONObject params;
        private String method;

        public Builder topic(String topic) {
            this.topic = topic;
            return this;
        }

        public Builder params(JSONObject params) {
            this.params = params;
            return this;
        }

        public Builder method(String method) {
            this.method = method;
            return this;
        }


        public ResponseRpc build() {
            return new ResponseRpc(this);
        }

    }

    private boolean isResponseDeviceStatus() {
        return !TextUtils.isEmpty(this.method) && method.equals(MqttConstants.ServerRpcMethod.GET_DEVICE_STATUS);
    }

    private boolean isRequestLocation() {
        return !TextUtils.isEmpty(this.method) && method.equals(MqttConstants.ServerRpcMethod.REQ_LOC);
    }

    private boolean isRequestVoipCall() {
        return !TextUtils.isEmpty(this.method) && method.equals(MqttConstants.ServerRpcMethod.REQ_VOIP_CALL);
    }

    private boolean isRequestOperateDevice() {
        return !TextUtils.isEmpty(this.method) && method.equals(MqttConstants.ServerRpcMethod.REQ_OPERATE_DEVICE);
    }

    private boolean isRequestDeviceFriend() {
        return !TextUtils.isEmpty(this.method) && method.equals(MqttConstants.ServerRpcMethod.REQ_DEVICE_FRIEND);
    }

    private boolean isRequestDeviceDebugData() {
        return !TextUtils.isEmpty(this.method) && method.equals(MqttConstants.ServerRpcMethod.REQ_DEVICE_DEBUG_DATA);
    }
}
